import {
	addNotifyConfigList,
	getNotifyConfigList,
	getNotifyTemplateList,
	invokeNotifyConfigList,
	modifyNotifyConfigList,
	removeNotifyConfigList
} from "@/api/modules/notification";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import BaseSearchForm from "@/components/SearchForm/BaseSearchForm";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { showTips, confirm, generateUUID, showMsg, deepClone } from "@/utils/util";
import "../product/product.scss";
import ConfigDetail from "./components/configDetail";
import { MessageType } from "@/enums/messageEnum";
import { notifyTemplateType, notifyUserType } from "@/utils/constants";
import { ComponentInternalInstance, getCurrentInstance } from "vue";

export default defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const proTableRef = ref();
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "name", label: proxy?.$t("notifyconfig.tablist_label.name"), width: "180" },
			{ prop: "status", label: proxy?.$t("notifyconfig.tablist_label.status"), width: "100" },
			{ prop: "sendWay", label: proxy?.$t("notifyconfig.tablist_label.send_way"), width: "200" },
			{ prop: "templateId", label: proxy?.$t("notifyconfig.tablist_label.template") },
			{ prop: "operate", label: proxy?.$t("notifyconfig.tablist_label.operate"), width: "200" }
		];
		const buttonsList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			buttonsList.value = await useAuthButtons();
		});
		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};
		const getTableList = async (params: any) => {
			return getNotifyConfigList(params);
		};
		const currentItem = ref({ id: "", source: "1", sendTargetType: notifyUserType.systemUser });
		const handerBtn = async (fn: string, row: any) => {
			let selected = row.selectList || [row];
			switch (fn) {
				case "add":
					detailDialog.visible = true;
					currentItem.value = { id: "", source: "1", sendTargetType: notifyUserType.systemUser };
					break;
				case "mod":
					if (selected.length != 1) {
						showMsg(proxy?.$t("notifyconfig.msg.mod"), MessageType.warning);
						return;
					}
					detailDialog.visible = true;
					currentItem.value = deepClone(selected[0]);
					break;
				case "del":
					if (!selected.length) {
						showMsg(proxy?.$t("notifyconfig.msg.del"), MessageType.warning);
						return;
					}
					confirm({ content: proxy?.$t("notifyconfig.confirm.del") }).then(async (flag: any) => {
						if (!flag) {
							return;
						}
						submitDel({ ids: selected.map((item: any) => item.id) });
					});
					break;
				case "test":
					let { code, message } = await invokeNotifyConfigList({
						id: selected[0].id,
						data: {
							sn: "通知测试",
							devName: "设备",
							variable: "告警变量标识",
							variableName: "告警变量名",
							currentVal: "告警值",
							alarmType: "告警类型",
							alarmLevel: "告警级别",
							timestamp: "告警时间"
						}
					});
					showTips(code, proxy?.$t("notifyconfig.card_label.test"), message);
					break;
			}
		};
		const detailDialog = reactive({ visible: false, title: proxy?.$t("notifyconfig.dialog_title.detail") });
		const submitDel = async (param: { ids: string[] }) => {
			let { code, message } = await removeNotifyConfigList(param);
			let ok = showTips(code, proxy?.$t("notifyconfig.tips.remove"), message);
			if (ok) {
				proTableRef.value.reset();
			}
		};
		const submit = async () => {
			if (currentItem.value.id) {
				let { code, message } = await modifyNotifyConfigList({ ...currentItem.value });
				let ok = showTips(code, proxy?.$t("notifyconfig.tips.modify"), message);
				if (ok) {
					detailDialog.visible = false;
					proTableRef.value.getTableList();
				}
			} else {
				let { code, message } = await addNotifyConfigList({ ...currentItem.value, id: generateUUID() });
				let ok = showTips(code, proxy?.$t("notifyconfig.tips.add"), message);
				if (ok) {
					detailDialog.visible = false;
					proTableRef.value.getTableList();
				}
			}
		};
		const state = reactive({
			searchParam: {} as any,
			searchColumns: [{ key: "name", label: proxy?.$t("notifyconfig.search_label.name") }]
		});

		const templateInfo = ref<{ content: string; name: string }>({ content: "", name: "" });
		const loadTemplate = async (templateId: string) => {
			showContent.value = templateId;
			let { result } = await getNotifyTemplateList({ id: templateId });
			templateInfo.value = result[0] || {};
		};
		const showContent = ref("");
		return () => {
			return (
				<div class="notify-config-page">
					{detailDialog.visible && (
						<ConfigDetail
							title={detailDialog.title}
							v-model:visible={detailDialog.visible}
							detail={currentItem.value}
							onSubmit={submit}
						></ConfigDetail>
					)}
					<BaseSearchForm
						class="mb-4"
						searchItems={state.searchColumns}
						search={state.searchParam}
						onFeatch={() => proTableRef.value.reset()}
					></BaseSearchForm>
					<ProTable
						ref={proTableRef}
						columns={columns}
						requestApi={getTableList}
						dataCallback={dataCallback}
						initParam={state.searchParam}
						custSearch
					>
						{{
							tableHeader: (scope: any) => {
								return buttonsList.value?.map((item: any) => {
									return (
										<el-button class={`iconfont ${item.icon}`} type={item.btnClass} onClick={() => handerBtn(item.path, scope)}>
											{item.menuName}
										</el-button>
									);
								});
							},
							status: (scope: any) => {
								return scope.row.status == 1 ? "启用" : "停用";
							},
							templateId: (scope: any) => {
								return Object.entries(JSON.parse(scope.row.templateId)).map(item => {
									return (
										<el-popover
											auto-close={3000}
											show-after={500}
											width="380px"
											onShow={() => loadTemplate(item[1]! as string)}
											title={
												item[0] == notifyTemplateType.sms
													? proxy?.$t("notifyconfig.popover_title.sms")
													: proxy?.$t("notifyconfig.popover_title.email")
											}
										>
											{{
												reference() {
													return (
														<el-link type="primary">
															{item[0] == notifyTemplateType.sms
																? proxy?.$t("notifyconfig.link.sms")
																: proxy?.$t("notifyconfig.link.email")}
														</el-link>
													);
												},
												default() {
													return (
														<div class="leading-8">
															<div class="flex">
																<div class="w-20">{proxy?.$t("notifyconfig.card_label.name")}</div>
																<div class="flex-1">{templateInfo.value.name}</div>
															</div>
															<div class="flex">
																<div class="w-20">{proxy?.$t("notifyconfig.card_label.content")}</div>
																<div class="flex-1">{templateInfo.value.content}</div>
															</div>
														</div>
													);
												}
											}}
										</el-popover>
									);
								});
							},
							sendWay: (scope: any) => {
								return Object.keys(JSON.parse(scope.row.templateId)).map((item: string) => {
									return (
										<el-tag type={item == "1" ? "" : "success"} class="mr-2" effect="dark">
											{item == "1" ? "短信" : "邮件"}
										</el-tag>
									);
								});
							},
							operate: (scope: any) => {
								return (
									<>
										{buttonsList.value
											.filter((item: any) => item.path == "del")
											.map((item: any) => {
												return (
													<el-popconfirm
														title={proxy?.$t("notifyconfig.confirm.operate")}
														popper-class="jsonform-tooltip"
														onConfirm={() => submitDel({ ids: [scope.row.id] })}
													>
														{{
															reference: () => {
																return (
																	<el-link type="danger">
																		<i class="iconfont icontrash-2"></i>
																		{item.menuName}
																	</el-link>
																);
															}
														}}
													</el-popconfirm>
												);
											})}
										<el-link
											type="primary"
											link
											class="iconfont iconbx-file"
											disabled={!buttonsList.value.find((item: any) => item.path == "mod")}
											onClick={() => handerBtn("mod", scope.row)}
										>
											{proxy?.$t("notifyconfig.card_label.modify")}
										</el-link>
										<el-link type="warning" link class="iconfont iconbx-test-tube" onClick={() => handerBtn("test", scope.row)}>
											{proxy?.$t("notifyconfig.card_label.test")}
										</el-link>
									</>
								);
							},
							empty: () => {
								return (
									<Empty
										class="text-left leading-6"
										title={proxy?.$t("notifyconfig.empty.title")}
										subtitle={proxy?.$t("notifyconfig.empty.subtitle")}
										onAdd={() => handerBtn("add", {})}
									/>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
